package com.haima.web.controller.common;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haima.common.config.HiMaConfig;
import com.haima.common.utils.AliyunOssUploadUtils;
import com.haima.common.utils.DateUtils;
import com.haima.common.utils.SecurityUtils;
import com.haima.system.service.ISysConfigService;
import com.haima.ziliao.domain.PDayinCar;
import com.haima.ziliao.domain.PDayinconfig;
import com.haima.ziliao.domain.PZiliao;
import com.haima.ziliao.service.IPDayinCarService;
import com.haima.ziliao.service.IPDayinconfigService;
import com.haima.ziliao.service.IPZiliaoService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.haima.common.constant.Constants;
import com.haima.common.core.domain.AjaxResult;
import com.haima.common.utils.StringUtils;
import com.haima.common.utils.file.FileUploadUtils;
import com.haima.common.utils.file.FileUtils;
import com.haima.framework.config.ServerConfig;

/**
 * 通用请求处理
 * 
 * @author hima
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IPZiliaoService ziliaoService;

    @Autowired
    private IPDayinconfigService dayinconfigService;
    @Autowired
    private IPDayinCarService pDayinCarService;

    @Autowired
    private ISysConfigService configService;

    private static final String FILE_DELIMETER = ",";



    @GetMapping("/checkToken")
    public AjaxResult checkToken()
    {
        return SecurityUtils.checkToken();
    }


    @GetMapping("/getPhoneConfig")
    public AjaxResult getPhoneConfig()
    {
        Map<String,Object> map = new HashMap<>();
        String lxs = configService.selectConfigByKey("lvxingshe.phone");
        String jj = configService.selectConfigByKey("jiajiao.phone");
        String jz = configService.selectConfigByKey("jiazhang.phone");

        map.put("lxs",lxs);
        map.put("jj",jj);
        map.put("jz",jz);

        return AjaxResult.success(map);
    }
    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = HiMaConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = HiMaConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @Async
    @PostMapping("/uploadZiliao")
    public AjaxResult uploadZiliao(MultipartFile file, PZiliao pZiliao) throws Exception
    {
        try
        {
            //获取文件MD5
//            String md5 = FileUtils.fileMd5(file);

//            PZiliao zl = ziliaoService.getOne(new QueryWrapper<PZiliao>().eq("md5",md5));
//            if(zl!=null){
//                url = zl.getPath();
//            }else{
//                url = AliyunOssUploadUtils.uploadFile(file);
//            }


            String px = FileUploadUtils.getExtension(file);

            InputStream inputStream = file.getInputStream();

            Integer totalPage = 0;
            if("PDF".equals(px.toUpperCase())){
                PDDocument document = PDDocument.load(inputStream);
                totalPage = document.getNumberOfPages();
            }else{
                if("DOC".equals(px.toUpperCase())){
                    return AjaxResult.error("不支持doc文件");
                }else{
                    ZipSecureFile.setMinInflateRatio(0.001);
                    XWPFDocument document = new XWPFDocument(inputStream);
                    totalPage = document.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
                }
            }

            String url = AliyunOssUploadUtils.uploadFile(file);

            if(url.isEmpty()){
                return AjaxResult.error(file.getName()+"上传失败");
            }

            String size = FileUtils.getFileSize(file);
            pZiliao.setTitle(file.getOriginalFilename());
            pZiliao.setPath(url);
            pZiliao.setPageNum(totalPage);
            pZiliao.setFileSize(size);
//            pZiliao.setMd5(md5);
            pZiliao.setAddTime(DateUtils.getNowDate());

            ziliaoService.insertPZiliao(pZiliao);

            return AjaxResult.success(pZiliao);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    public static String getFileExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int index = filename.lastIndexOf('.');
        if (index == -1) {
            return null;
        } else {
            return filename.substring(index + 1);
        }
    }
    @PostMapping("/uploadDyCar")
    public AjaxResult uploadDyCar(MultipartFile file, String name) {
        PDayinCar dayinCar = new PDayinCar();
        try {
            String url = AliyunOssUploadUtils.uploadFile(file);

            InputStream inputStream = file.getInputStream();
            PDDocument document = PDDocument.load(inputStream);

            Integer totalPage = document.getNumberOfPages();

//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("url", url);
//            ajax.put("fileName", name);
//            ajax.put("newFileName", FileUtils.getName(url));
//            ajax.put("originalFilename", file.getOriginalFilename());



            dayinCar.setUid(SecurityUtils.getUserId());
            dayinCar.setName(name);
            dayinCar.setYeshu(totalPage);
            dayinCar.setStatus(1);
            dayinCar.setFilePath(url);
            dayinCar.setAddTime(DateUtils.getNowDate());
            dayinCar.setFs(1);

            PDayinconfig config = dayinconfigService.selectPDayinconfigById(1L);
            BigDecimal dm = config.getDanmian();
            BigDecimal jine = dm.multiply(new BigDecimal(totalPage)).multiply(new BigDecimal(dayinCar.getFs()));

            dayinCar.setJine(jine);

            pDayinCarService.insertPDayinCar(dayinCar);

            return AjaxResult.success(dayinCar);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = HiMaConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @CrossOrigin
    @PostMapping("/uploadOSS")
    public AjaxResult uploadFileOSS(MultipartFile file) {
        System.out.println(file);
        try {
            String url = AliyunOssUploadUtils.uploadFile(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", FileUtils.getName(url));
            ajax.put("newFileName", FileUtils.getName(url));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = HiMaConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
